﻿
using System;

using MskEdit.Sdk ;


namespace MskEdit.Dxf.Representation
{
    public class DxfSignature
    {
        private DxfCodeTagPair[]    codeTagPairs_ ;
        

        public DxfSignature( string code0, string tag0, string code1, string tag1 ) {
        
            codeTagPairs_ = new DxfCodeTagPair[] {
                new DxfCodeTagPair( code0, tag0 ), 
                new DxfCodeTagPair( code1, tag1 ) 
            } ;
            
        }


        public DxfSignature( string code0, string tag0, string code1, string tag1, string code2, string tag2 ) {
        
            codeTagPairs_ = new DxfCodeTagPair[] {
                new DxfCodeTagPair( code0, tag0 ), 
                new DxfCodeTagPair( code1, tag1 ), 
                new DxfCodeTagPair( code2, tag2 ) 
            } ;
            
        }
        
                
        public SdkSubrange? TryGetSubrange( string[] allLines, ref int lineNo, SdkSubrange? fallbackValue ) {
                
            int internalLineNo = lineNo ;     
            
            if ( !codeTagPairs_[0].IsFirst( allLines, ref internalLineNo ) )
                return fallbackValue ;

            // Reset internalLineNo if start-pattern happens to match end-pattern.
            // That means start-pattern is more general that the end-pattern
            // so the terminator may be hidden in the first line.
            
            if ( codeTagPairs_[0].IsMatching( codeTagPairs_[1] ) )
                internalLineNo = lineNo ;
                
            int? end = codeTagPairs_[1].TryFindFirst( allLines, ref internalLineNo, null ) ;
            if ( !end.HasValue )
                throw new SdkException( "Failed to find primary end of DXF subrange in line set." ) ;
                
            if ( codeTagPairs_.Length == 3 ) {
                end = codeTagPairs_[2].TryFindFirst( allLines, ref internalLineNo, null ) ;
                if ( !end.HasValue )
                    throw new SdkException( "Failed to find secondary end of DXF subrange in line set." ) ;
            }
            
            if ( internalLineNo == lineNo )
                return fallbackValue ;
                
            SdkSubrange? sectionSubrange = new SdkSubrange( lineNo, internalLineNo - lineNo ) ;
            
            lineNo = internalLineNo ;
            
            return sectionSubrange ;
        }

    }
}
